/* eslint-disable */
const { Controller } = require('egg');
const fs = require('fs');
const path = require('path')

const awaitWriteStream = require('await-stream-ready').write;

class FileController extends Controller {
  //文件上传
  async upload() {
    const { ctx, app } = this;
    const size = ctx.request.header['content-length'];
    const stream = await ctx.getFileStream();
    const { fileSize } = app.config.multipart;
    if (size > fileSize) {
      ctx.body = {
        code: 1,
        message: `文件大小不可超过${fileSize / 1024 / 1024}Mb`,
      }
      return
    }
    const fileName = stream.filename
    const extension = path.extname(stream.filename)
    const uploadBasePath = 'app/public/uploads';
    const target = path.join(uploadBasePath, fileName)
    const writeStream = fs.createWriteStream(target)
    try {
      await awaitWriteStream(stream.pipe(writeStream))
      ctx.body = {
        code: 0,
        data: {
          fileName,
          filePath: 'http://localhost:8888' + path.join('/public/uploads', fileName).replace(/\\/g, '/'),
          size,
          extension
        }
      }
    } catch (error) {
      ctx.throw(500, error);
      throw error;
    }
  }
}
module.exports = FileController;